package leetcode.ArrayAndString;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SpiralOrder {

    /**
     * 给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。
     * @param matrix
     * @return
     */
    public static List<Integer> findDiagonalOrder(int[][] matrix) {


        Integer[] result = new Integer[0];
        List<Integer> list = new ArrayList<>();

        if (matrix == null || matrix.length == 0) {
            return list;
        }
        int  status = 1;

        int hight = matrix.length;
        int weight = matrix[0].length;
        result = new Integer[hight * weight];

        int resultIndex = 0;
        int x = 0;
        int y = 0;

        int up = 0;
        int down = 0;
        int right = 0;
        int left = 0;
        for (int i = 0; i < hight * weight; i++) {
            result[resultIndex++] = matrix[y][x];
            if (status ==1) {  //右移动
                x++;
                if (x == weight-right) {
                    status = 2;
                    x--;
                    y++;
                    up++;
                }
            } else if(status ==2) { //下移动
                y++;
                if (y == hight-down) {
                    status = 3;
                    x--;
                    y--;
                    right++;
                }
            }else if(status ==3 ){  // 左移动
                x--;
                if(x<left){
                    status = 4;
                    x++;
                    y--;
                    down++;
                }
            }else if(status ==4){
                y--;
                if(y<up){
                    status = 1;
                    x++;
                    y++;
                    left++;
                }
            }
        }
        list = Arrays.asList(result);
        return list;
    }

    public static void main(String args[]) {
        int[][] nums = addList();
        long start = System.currentTimeMillis();
        System.out.println(findDiagonalOrder(nums));
        long end = System.currentTimeMillis();

        System.out.println("time = " + (end - start));

    }

    private static int[][] addList() {
        int[][] bb = {{1,2,3,4,5,6},{16,17,18,19,20,7},{15,24,23,22,21,8},{14,13,12,11,10,9}};
        return bb;
    }


}
